/* This file is part of LlamaSlayers Ajax Chat
 *
 * The source code is released under the GNU GPL free software license, version 3.
 * Updates can be found at http://llamaslayers-ajax-chat.googlecode.com/
 */
var user = location.hash.substr(1);
$(function(){
	document.title = 'Login as ' + user;
	$('h1').text('Login as ' + user);
});
$.getScript('des.js', function(){
	$.get(
		'user.php',
		{g: 'key'},
		function(key){
			$('form').empty().append('<label for="pass">Password:</label>').append($('<input type="password"/>').attr({id: 'pass'})).submit(function(){
				var pass = stringToHex(des(key, $('#pass').val(), 1, 0, null, 0));
				$.getJSON(
					'user.php',
					{	g: 'login',
						u: user,
						p: pass },
					function (data) {
						switch (data[0]) {
							case 'err!':
								$('form').text('There was an error logging you in.');
								break;
							case 'pre.':
								$('form').text('You are already logged in.');
								break;
							case 'yes!':
								$('form').text('Login successful. ').append($('<a/>').text('Go back to the chat.').click(function(){
									history.go(-1);
								}));
								break;
							case 'pass':
								$('form').text('Invalid password.');
								break;
							case 'who?':
								$('form').text('This username is not registered yet, but it can be. If you want it, you can ').append($('<a/>').text('register it now.').one('click', function(){
									$.get(
										'user.php',
										{	g: 'register',
											u: user,
											p: pass },
										function (result) {
											if (result == 1)
												$('form').text('The registration was successful. ').append($('<a/>').text('Go back to the chat.').click(function(){
													history.go(-1);
												}));
											else
												$('form').text('The registration failed.');
										},
										'text'
									);
								}));
								break;
							case 'nevr':
								$('form').text('This username is either too short or blocked.');
								break;
						}
					}
				);
				return false;
			});
		},
		'text'
	);
});